package com.kujawnode.config;

import com.kujawnode.config.filter.TokenVerifyFilter;
import com.kujawnode.config.handler.MyAuthenticationFailureHandler;
import com.kujawnode.config.handler.MyAuthenticationSuccessHandler;
import com.kujawnode.config.handler.MyLogoutSuccessHandler;
import com.kujawnode.constant.Constants;
import jakarta.annotation.Resource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.logout.LogoutFilter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import java.util.Arrays;

/**
 * @version 1.0
 * @Author kujaw
 * @Date 2025/7/9 14:29
 * @注释
 */
@Configuration
public class SecurityConfig {

    @Resource
    private MyLogoutSuccessHandler myLogoutSuccessHandler;

    @Resource
    private MyAuthenticationSuccessHandler myAuthenticationSuccessHandler;

    @Resource
    private MyAuthenticationFailureHandler myAuthenticationFailureHandler;

    @Resource
    private TokenVerifyFilter tokenVerifyFilter;

    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Bean
    public SecurityFilterChain securityFilterChain(
            @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")HttpSecurity httpSecurity,
            CorsConfigurationSource configurationSource
    ) throws Exception {
        // 禁用跨站请求伪造
        return httpSecurity
                .formLogin((formLogin)->{
                    formLogin.loginProcessingUrl(Constants.LOGIN_URI)
                            .usernameParameter("loginAct")
                            .passwordParameter("loginPwd")
                            .successHandler(myAuthenticationSuccessHandler)
                            .failureHandler(myAuthenticationFailureHandler);
                })
                .authorizeHttpRequests((authorize)->{
                    authorize.requestMatchers(Constants.LOGIN_URI).permitAll()
                            .anyRequest().authenticated(); //其他请求拦截需要登录后才能访问
                })
                .csrf(AbstractHttpConfigurer::disable) // 禁用跨站请求伪造
                //支持跨域请求
                .cors((cors)->{
                    cors.configurationSource(configurationSource);
                })

                .sessionManagement((session)->{
                    //session创建策略
                    session.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
                })

                //添加自定义Filter
                .addFilterBefore(tokenVerifyFilter, LogoutFilter.class)
                //退出登录
                .logout((logout)->{
                    logout.logoutUrl("/api/logout")
                            .logoutSuccessHandler(myLogoutSuccessHandler);
                })
                .build();
    }

    @Bean
    public CorsConfigurationSource configurationSource(){
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.setAllowedOrigins(Arrays.asList("*")); //允许的请求源
        corsConfiguration.setAllowedMethods(Arrays.asList("*")); //允许任何请求方法post、get、put、delete、patch等
        corsConfiguration.setAllowedHeaders(Arrays.asList("*")); //允许任何请求头

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**",corsConfiguration);

        return source;
    }
}
